package com.zhuzi.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author MI
 * @ClassName XmlUtils.java
 * @createTime 2021年11月15日 14:32:00
 */
@Slf4j
public class XmlUtils {
    public static XmlMapper xmlMapper = new XmlMapper();

    static {
        //反序列化时，若实体类没有对应的属性，是否抛出JsonMappingException异常，false忽略掉
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //序列化是否绕根元素，true，则以类名为根元素
        xmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        xmlMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //XML标签名:使用骆驼命名的属性名，
        //xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
        //xml 头
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.setDefaultUseWrapper(false);
        //美化xml
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        xmlMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object param, JsonGenerator jsonGenerator, SerializerProvider paramSerializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
    }

    public static String jacksonBean2XML(Object value) {
        try {
            return xmlMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            log.error("实体转xml失败", e);
        }
        return null;
    }

    public static <T> T jacksonXML2Bean(String xmlStr, Class<T> clazz) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.setDefaultUseWrapper(false);
        //自动忽略无法对应pojo的字段
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return xmlMapper.readValue(xmlStr, clazz);
        } catch (IOException e) {
            log.error("xml字符串转实体失败", e);
        }
        return null;
    }
}
